package vip.xiaonuo.smzq.core.tools;

import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * <p>
 * 通用工具类
 * </p>
 *
 */

public class UniversalTool {

    /**
     * 判断实体bean中是否有null字段并赋值0
     * @param obj
     * @return
     */
    public static String checkObjectForNullFields(Object obj) {
        String result = "";

        try {
            // 获取类的BeanInfo对象，以便获取属性描述符
            PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(obj.getClass()).getPropertyDescriptors();

            for (PropertyDescriptor descriptor : propertyDescriptors) {
                Method getter = descriptor.getReadMethod();

                // 避免静态或非公有属性
                if (getter != null && getter.getDeclaringClass() != Object.class) {
                    Object value = getter.invoke(obj);
                    if (value == null) {
                        System.out.println("字段 " + descriptor.getName() + " 的值为 null");
                        result=result+ descriptor.getName()+":0,";

                    }else{
                        result=result+descriptor.getName()+":"+value+",";

                    }
                }
            }
        } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
            throw new RuntimeException("在检查对象字段时发生错误", e);
        }
        return "{" +result+"}";
    }







}
